<?php

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */
namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Db\Adapter\Adapter as DbAdapter;
use Application\Model\ServicesTable;
use Application\Model\ProjetTable;
use Application\Model\ProjetsUsersTable;
use Zend\Mvc\MvcEvent;
use Zend\Mvc\Router\Http\TranslatorAwareTreeRouteStack;
use Zend\Session\Container;
use Application\Form\ConnexionForm;
use Application\Form\InputFileForm;
use Application\Form\ProjetForm;
use Application\Form\DemandeForm;
use Application\Model\Intranet;
use Application\Model\UserTable;
use User\Controller\UserController;
use Application\Model\FileDownload;
use Application\Model\Demande;
use Zend\Mail;
use Zend\Form\Element\Date;
use Application\Model\FileTable;
use Application\Model\File;
use Application\Model\PersonnelTable;
use Application\Model\Personnel;
use Application\Form\InscriptionForm;
use Application\Model\Inscription;
use Application\Model\AgendaTable;
use Application\Model\Agenda;
use Application\Model\DemandesTable;
use Application\Model\Demandes;
use DateInterval;
use DateTime;


class IntranetController extends AbstractActionController {
	protected $serviceTable;
	protected $userTable;
	protected $fileTable;
	protected $projetTable;
	protected $projetUserTable;
	protected $personnalTable;
	protected $agendaTable;
	protected $demandesTable;
	
	
	public function intranetAction() {
		date_default_timezone_set('Europe/Paris');
		$user_session = new Container('user');
		$id = $user_session->id_user;
		$login = $user_session->login;
		if(isset($user_session) && $user_session->is_connected == 1){
			
			if($user_session->is_admin ==1)
			{
				return $this->redirect ()->toRoute ( 'admin', array (
						'controller' => 'Admin',
						'action' => 'admin'
				) );
				
			}else{
				$fileForm = new InputFileForm ();
				$demandeForm = new DemandeForm ();
				$projetForm  = new ProjetForm();
				$CV = $this->getFileTable()->getCVFile($id);
				$personnel =   $this->getPersonnelTable()->getPersonnellogin($login);	
				//$fichiers =   $this->getFileTable()->getFile($id);
				$fichiersSources =   $this->getFileTable()->getFile($id,'Fichiers sources');
				$autresfichiers =   $this->getFileTable()->getFile($id,'Autres');
				
				
				$agenda   = $this->getAgendaTable()->getTacheByUserId($id);
			/*	if($CV == null || $CV == "Error"){
					$CV = "Vous n'avez pas encore soumis votre CV. <br>";
				}
				
				if($fichiers == null || $fichiers == "Error"){
					$fichiers = "Vous n'avez pas encore de fichiers. <br>";
				}
			*/
				// grab the paginator from the AlbumTable
				$paginator = $this->getAgendaTable()->fetchAll();
				
				//print_r($paginator);
				// set the current page to what has been passed in query string, or to 1 if none set
//				$paginator->setCurrentPageNumber((int)$this->params()->fromQuery('page', 1));
				// set the number of items per page to 10
			//	$paginator->setItemCountPerPage(10);
				
// 				return new ViewModel(array(
// 						'paginator' => $paginator
// 				));
				
				return new ViewModel ( array (
						'fileform' => $fileForm,
						'demandeform' => $demandeForm ,
						'projetForm' =>$projetForm,
						'projet' =>$this->getProjetTable()->SelectById($id),
						'projet2' =>$this->getProjetsUsersTable()->SelectByIdUsers($id),
						//'fichiers' =>$fichiers,
						'fichiersSources' =>$fichiersSources,
						'autresfichiers' =>$autresfichiers,
						'CV' =>$this->getFileTable()->getCVFile($id),
						'personnel' => $personnel,
						'agenda' => $agenda,
						'paginator' => $paginator
				) );
			
			}
		} else {
			
			return $this->redirect ()->toRoute ( 'connexion', array (
					'controller' => 'Intranet',
					'action' => 'connexion' 
			),
			array(
	    	 				'query' => array('url' => 'intranet'),
	    	 		) );
		}
		
	//	return new ViewModel();
	}
	public function getUserTable() {
		if (! $this->userTable) {
			$sm = $this->getServiceLocator ();
			$config = $sm->get ( 'config' );
			$config = $config ['db'];
			$dbAdapter = new DbAdapter ( $config );
			// return $dbAdapter;
			$table = new UserTable ( $dbAdapter );
			// $this->userTable = $sm->get($table);
			$this->userTable = $table;
		}
		return $this->userTable;
	}
	/*
	 * AGENDA
	*/
	
	public function getAgendaTable() {
		if (! $this->agendaTable) {
			$sm = $this->getServiceLocator ();
			$config = $sm->get ( 'config' );
			$config = $config ['db'];
			$dbAdapter = new DbAdapter ( $config );
			$table = new AgendaTable ( $dbAdapter );
			$this->agendaTable = $table;
		}
		return $this->agendaTable;
	}
	
	/**
	 * Demande
	 */
	
	public function getDemandesTable()
	{
		if (!$this->demandesTable) {
			$sm = $this->getServiceLocator();
			$config = $sm->get('config');
			$config = $config['db'];
			$dbAdapter = new DbAdapter($config);
			//return $dbAdapter;
			$table = new DemandesTable($dbAdapter);
			//$this->userTable = $sm->get($table);
			$this->demandesTable = $table;
		}
		return $this->demandesTable;
	}
	
	public function getPersonnelTable() {
		if (! $this->personnalTable) {
			$sm = $this->getServiceLocator ();
			$config = $sm->get ( 'config' );
			$config = $config ['db'];
			$dbAdapter = new DbAdapter ( $config );
			// return $dbAdapter;
			$table = new PersonnelTable ( $dbAdapter );
			// $this->userTable = $sm->get($table);
			$this->personnalTable = $table;
		}
		return $this->personnalTable;
	}
	
	public function getFileTable() {
		if (! $this->fileTable) {
			$sm = $this->getServiceLocator ();
			$config = $sm->get ( 'config' );
			$config = $config ['db'];
			$dbAdapter = new DbAdapter ( $config );
			// return $dbAdapter;
			$table = new FileTable ( $dbAdapter );
			// $this->userTable = $sm->get($table);
			$this->fileTable = $table;
		}
		return $this->fileTable;
	}
	
	public function getProjetTable()
	{
		if (!$this->projetTable) {
			$sm = $this->getServiceLocator();
			$config = $sm->get('config');
			$config = $config['db'];
			$dbAdapter = new DbAdapter($config);
			//return $dbAdapter;
			$table = new ProjetTable($dbAdapter);
			//$this->userTable = $sm->get($table);
			$this->projetTable = $table;
		}
		return $this->projetTable;
	}
	
	public function getProjetsUsersTable()
	{
		if (!$this->projetUserTable) {
			$sm = $this->getServiceLocator();
			$config = $sm->get('config');
			$config = $config['db'];
			$dbAdapter = new DbAdapter($config);
			//return $dbAdapter;
			$table = new ProjetsUsersTable($dbAdapter);
			//$this->userTable = $sm->get($table);
			$this->projetUserTable = $table;
		}
		return $this->projetUserTable;
	}
	
	public function connexionAction() {
		$user_session = new Container('user');
		if(!isset($_REQUEST['url'])){
			$_REQUEST['url'] = 'intranet';
		}
		if ($user_session->is_connected == 0) {
			$form = new ConnexionForm();
			return new ViewModel ( array (
				
					'form' => $form,
					'redirect'=>$_REQUEST['url']
			) );
			
		} else {
			
			return $this->redirect ()->toRoute ( $_REQUEST['url'] );
		}
	}
	public function deconnexionAction() {
		unset ( $_SESSION ['user'] );	
		return $this->redirect ()->toRoute ( 'connexion', array (
				'controller' => 'Intranet',
				'action' => 'connexion' 
		) );
	}
		    
	
	public  function demandeAction(){
		date_default_timezone_set('Europe/Paris');
		$user_session = new Container('user');
		$id = $user_session->id_user;
		$login = $user_session->login;
		
		if(isset($user_session) && $user_session->is_connected == 1){	
		
			$demandeForm = new DemandeForm ();
			$request = $this->getRequest ();
			date_default_timezone_set('Europe/Paris');
			$user_session = new Container('user');
			$id_user = $user_session->id_user;
			$nom = $user_session->nom;
			$prenom  = $user_session->prenom;
			$from    = $user_session->email;
				
			if ($request->isPost ()) {
				 
				$demand = new Demande();
				$demandeForm->setInputFilter ( $demand->getInputFilter () );
				$demandeForm->setData ( $request->getPost () );
				 
				 
				if ($demandeForm->isValid ()) {
		
		
					$datas = $demandeForm->getData() ;
					//$datas->exchangeArray($form->getData());
		
					$typedemande = $datas['type_demande'];
					$demande = $datas['demande'];
					
					$diff1Day = new DateInterval('P1D');
					$dat_creat = new DateTime();
					$dat_creat = date_format($dat_creat, 'Y-m-d');
				//	$dat_creat = $dat_creat->format('Y-m-d');
					$date_limite = new DateTime();
					
					$date_limite->add($diff1Day);
					$date_limite = date_format($date_limite, 'Y-m-d');
				
					
					switch ($typedemande) {
					
						case 'Absence':
							$type_demande =1;
							break;
						case 'Formation':
							$type_demande =2;
							break;
						case 'Support':
							$type_demande =3;
							break;
						case 'Matériel':
							$type_demande =4;
							break;
						case 'Suggestions':
							$type_demande =5;
							break;
						case 'Réclamation':
							$type_demande =6;
							break;
						case 'Autres':
							$type_demande =7;
							break;
					}
					
					$type_tache ='2';//validation deamande
					$this->getDemandesTable()-> addDemande($id_user,$type_demande,$demande,$dat_creat, $nom, 1,0,0,null);
					$id_demande = $this->getDemandesTable()->getLastInsertValue();
					
					$this->getAgendaTable()->addAgenda($type_tache,$id_demande,$id_user, 'Validation '.$typedemande,$demande,$dat_creat,$date_limite, $nom, 0,0,null);
				
					
				/*
					$mail = new Mail\Message();
					$mail->setBody($demande)
					->setFrom('application@lamisabdi.com', $nom)
					->addTo('lamisa.burundi@gmail.com', $nom)
					->setSubject($typedemande);
		
					$transport = new Mail\Transport\Sendmail();
					$transport->send($mail);
		*/
						
					$fileForm = new InputFileForm ();
					$result ='Votre demande a été envoyé avec succès';
						
					return $this->redirect ()->toRoute ( 'mylamisa' );
				}else {
    				
			    	 $this->redirect ()->toRoute ( 'connexion', array (
			    		'controller' => 'Intranet',
			    		'action' => 'connexion'
			    	 ) );
		    	}
				
			}else{
				$fileForm = new InputFileForm ();
				//	$demandeForm = new DemandeForm ();
				return new ViewModel(array(
						'fileform' =>$fileForm,
						'demandeform' =>$demandeForm,
				));
			}
		}
	
	}
	    public  function  updateagendaAction(){
	    
	    	$reponse = $_POST['reponse'];
	    	$id_tache = $_POST['id_tache'];
	    	$id_demande = $_POST['id_demande'];

	    	
	    	// mis à jour agenda
	    	$this->getAgendaTable()->updateAgenda($reponse,$id_tache);
	    	// mis à jour demande
	    	$this->getDemandesTable()->updateDemande($reponse,$id_demande);
	    		
	    		    	
	    	return $this->redirect ()->toRoute ( 'mylamisa' );
	    }
	     
	    public function inscriptionAction(){
	    	 
	    	$form_insc = new InscriptionForm();
	    	$request = $this->getRequest ();
	    	if ($request->isPost ()) {
	    
	    		
	    		$sample = new Inscription();
	    		//$form_insc->setInputFilter($sample->getInputFilter());
	    		//$form_insc->setData($request->getPost());
	    		
	    		print_r($request->getPost()['nom']);
	    		//if ($form_insc->isValid()) {
	    		$datas = $request->getPost();
	    			$nom  = $datas['nom'];
	    			$prenom  = $datas['prenom'];
	    			$fonction  = $datas['fonction'];
	    			$adresse  = $datas['adresse'];
	    			$email  = $datas['email'];
	    			$telephone = $datas['telephone'];
	    			$login = $datas['login'];
	    			$password  = $datas['password'];
	    			$password2  = $datas['password2'];
	    			 
	    		//	$objet  = $datas['motif'];
	    			$date_inscrip =  $datas['date_inscrip'];
	    			 
	    			//	echo isPasswordEqual($password,$password2);
	    			 
	    			if($password != $password2){
	    				 
	    				$erreur = 'Erreur de confirmation du mot de passe';
	    				return new ViewModel(array(
	    						'form'=>$form_insc,
	    						'erreur' =>$erreur,
	    				));
	    			}
	    			 
	    			//$result = $this->getPersonnelTable()->addPersonnel($nom, $prenom, $fonction, $email, $telephone, $login, $password, $date_inscrip);
	    			try {
	    				$this->getPersonnelTable()->addPersonnel($nom, $prenom, $login,$fonction,$email, $telephone,$adresse, md5($password),$date_inscrip);
	    			} catch (\PDOException $e) {
	    
	    				throw new Exception\InvalidQueryException(
	    						'Statement could not be executed ',
	    						null,
	    						$e
	    				);
	    			}
	    			 
		    
	    			return new ViewModel(array(
	    					'result'=>'<p style="padding-left: 8px;">Votre compte a été enregistré.Vous veillez attendre sa
    					 validation pour vous connecter <br><br> Merci <br><br>
    					<a href="#"> Cliquez ici pour revenir à la page d\'acceuil </a>
    	
    					</p>
    	
    					',
	    			));
	    	}
	    	return new ViewModel(array(
	    			'form'=>$form_insc,
	    	));
	    }
	    
	    public function downloadfileAction()
	    {
	    	date_default_timezone_set('Europe/Paris');
	    	$user_session = new Container('user');
	    	$login = $user_session->login;
	    	$id_user = $user_session->id_user;
	    	
	    	if ($id_user != null){
		    	$dat_creat = date("Y-m-d");
		    	$today = date("Ymd");
		    	$typefichier = $_POST['typefile'];
		    	
	
		    	if ($typefichier == "Avatar") {
		    		$dossier ='../lamisa.burundi/public/img/avatar/';
		    	}elseif($typefichier == "CV") {
		    		$dossier ='fichiers/CV';
		    	}else {
		    		$dossier = 'fichiers/projets/'.$today;
		    	}
		    
		    	
		    	$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
		  
				if (!file_exists($dossier)){    			
		    			mkdir($dossier, 0777, true);
					//	print_r($dossier);
		    	}
				
		    	if ($fn) {
		    	
		    		// AJAX call
		    		file_put_contents(
		    		'../lamisa.burundi/fichiers/'.$dossier.'/' . $fn,
		    		file_get_contents('php://input')
		    		);
		    		echo'ajax';
		    		exit();
		    	
		    	}
		    	else {
	
		    		// form submit
					  		
		    		$files = $_FILES['fileselect'];   		
		    		foreach ($files['error'] as $id => $err) {
		    			if ($err == UPLOAD_ERR_OK) {
		    				$fn = $files['name'][$id];
		    				
		    				$infosfichier =pathinfo($fn);
		    				$extension_upload = $infosfichier['extension'];
	    			    				
		    				if ($typefichier == "Avatar") { 	    					
		    					$fn = $login.'.'.$extension_upload;	    					
		    					move_uploaded_file( $files['tmp_name'][$id],'../lamisa.burundi/public/img/avatar/'. $fn);	    					
		    					$adress ='../lamisa.burundi/public/img/avatar/';
		    				}elseif($typefichier == "CV"){	    					
								$adress = '/lamisa.burundi/fichiers/'.$dossier;
		    					move_uploaded_file( $files['tmp_name'][$id],'../lamisa.burundi/'.$dossier.'/' . $fn);
		    				}else{
								$adress = '/lamisa.burundi/fichiers/projets/'.$dossier;
		    					move_uploaded_file( $files['tmp_name'][$id],'../lamisa.burundi/'.$dossier.'/' . $fn);
							}			
		    				$this->getFileTable()->addFile($id_user, $fn,$adress , $typefichier,$dat_creat);	    				
		    			}
		    		}
		    		
		    		//return $this->redirect ()->toRoute ( 'intranet' );
		    		return $this->redirect ()->toRoute ( 'connexion', array (
		    				'controller' => 'Intranet',
		    				'action' => 'connexion',
		    				'params'=> $dossier
		    		) );
		    	
		    	}
	    	}else{
	    		return $this->redirect ()->toRoute ( 'connexion', array (
	    				'controller' => 'Intranet',
	    				'action' => 'connexion',
	    				'params'=> $dossier
	    		) );
	    		
	    	}	
	    }
	    
	    public function adminAction(){
	    	return new ViewModel();
	    }
	    
	    public function   myLamisaAction(){
	    	
	    	
	    	//return new ViewModel();
	    }
}
